import React, { useState, useImperativeHandle, useEffect } from 'react';
import { Form, Input, Select, Modal, message } from 'antd';
import { update } from '../api';

/**
 * 系统管理/权限管理/角色管理/编辑弹窗
 */
const EditForm = ({ getAll }: any, ref: any) => {
  const [form] = Form.useForm();
  const [editData, setEditData] = useState<RoleAPI.DataType>();
  const [visible, setVis] = useState({ open: false, id: '0' });
  useImperativeHandle(ref, () => ({ setVis, setEditData }));

  const onCancel = () => {
    setVis({ open: false, id: '0' });
  };

  const onFinish = () => {
    form.validateFields().then(async (values) => {
      const data = { ...values, id: visible.id };
      const res = await update(data);
      if (res.code === 200) {
        getAll();
        message.success(res.msg);
      } else {
        message.error(res.msg);
      }
      form.resetFields();
      onCancel();
    });
  };

  useEffect(() => {
    if (visible.id != '0') {
      form.setFieldsValue(editData);
      let statusData;
      if (editData?.status === '启用') {
        statusData = 1;
      } else {
        statusData = 0;
      }
      form.setFieldValue('status', statusData);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible.id]);

  const rules = [{ required: true, message: '不能为空' }];

  return (
    <Modal
      title="修改用户"
      width={600}
      open={visible.open}
      onOk={onFinish}
      onCancel={onCancel}
      afterClose={() => form.resetFields()}
    >
      <Form name="editRole" autoComplete="off" form={form}>
        <Form.Item
          label="角色名称"
          name="name"
          rules={[
            { required: true, message: '' },
            () => ({
              validator(_, value) {
                if (value.trim() !== '') {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('请输入角色名称!'));
              },
            }),
          ]}
        >
          <Input placeholder="请输入角色名称" />
        </Form.Item>

        <Form.Item label="描述" name="description" rules={rules}>
          <Input placeholder="请输入描述" />
        </Form.Item>

        <Form.Item label="状态" name="status" rules={rules}>
          <Select
            placeholder="是否启用角色"
            options={[
              { key: 1, value: 1, label: '启用' },
              { key: 0, value: 0, label: '禁用' },
            ]}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default React.forwardRef(EditForm);
